package com.orangelife.mobile.pay.biz;

import com.curry.android.http.OrangeDataHandler;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.curry.android.http.HttpUtil;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ConfirmOrderURL;
import com.orangelife.mobile.pay.interfaze.IOuttradenoCallBack;
import com.orangelife.mobile.pay.interfaze.IPayCallBack;
import com.orangelife.mobile.pay.interfaze.IPayManage;
import com.orangelife.mobile.util.SignUtils;
import com.orangelife.mobile.util.ToastHelper;
import com.thirdsdk.yintong.pay.utils.BaseHelper;
import com.thirdsdk.yintong.pay.utils.Constants;

public class PayManageImpl implements IPayManage {
    private OrederBean orederBean;
    private static final int APILAY_PAID = 1;
    private static final int LIST_ORDER = 2;
    private static final int RQF_PAY = 3;
    private IPayCallBack iPayCallBack;
    private IOuttradenoCallBack iOuttradenoCallBack;
    private List<String> list;

    public PayManageImpl(IPayCallBack iPayCallBack) {
        this.iPayCallBack = iPayCallBack;
    }

    public PayManageImpl(IOuttradenoCallBack iOuttradenoCallBack) {
        this.iOuttradenoCallBack = iOuttradenoCallBack;
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case APILAY_PAID:
                    /** 支付宝支付 */
                    ApliayResult resultObj = new ApliayResult((String) msg.obj);
                    String resultStatus = resultObj.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
                        iPayCallBack.success();
                    } else {
                        if (TextUtils.equals(resultStatus, "8000")) {
                            iPayCallBack.handling();
                        } else {
                            iPayCallBack.fail();
                        }
                    }
                    break;
                case LIST_ORDER:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        iOuttradenoCallBack.data(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case RQF_PAY:
                    JSONObject objContent = BaseHelper.string2JSON((String) msg.obj);
                    String retCode = objContent.optString("ret_code");
                    String retMsg = objContent.optString("ret_msg");
                    // 成功
                    if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
//                	  ToastHelper.getInstance()._toast(
//                              "支付成功，交易状态码：" + retCode);
                        iPayCallBack.success();
                    } else if (Constants.RET_CODE_PROCESS.equals(retCode)) {
                        String resulPay = objContent.optString("result_pay");
                        if (Constants.RESULT_PAY_PROCESSING
                                .equalsIgnoreCase(resulPay)) {
//                    	  ToastHelper.getInstance()._toast(
//                    			  objContent.optString("ret_msg") + "交易状态码："
//                                          + retCode);
                            iPayCallBack.handling();
                        }
                    } else {
                        //  失败
//                	  ToastHelper.getInstance()._toast(retMsg+
//                              "，交易状态码：" + retCode);
                        iPayCallBack.fail();
                    }
                    Log.e("retCode=", retCode);
                    Log.e("retMsg=", retMsg);
                    break;
                case Constant.WHAT_ERROR_HTTP:
                case Constant.WHAT_EXPIRE_ORDER:
                    ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
                    if (iOuttradenoCallBack != null) {
                        iOuttradenoCallBack.data(null);
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void setParameter(Context context, JSONObject jsonObject) {
        orederBean = new OrederBean();
        try {
            orederBean.setRas_Private(jsonObject.getString("privateKey"));
            // orederBean.setRas_Public(jsonObject.getString(
            // "aliPublicKey").toString());
            orederBean.setAlipay_number(jsonObject.getString("sellerEmail"));
            orederBean.setPartner_id(jsonObject.getString("partner"));
            orederBean.setOreder_Id(jsonObject.getString("outtradeno"));
            orederBean.setPrice(jsonObject.getString("totalCost"));
            orederBean.setDetail("商品购买详情");
            if ((jsonObject.getString("appNotifyUrl") != null)
                    || (!(jsonObject.getString("appNotifyUrl").equals("null")))) {
                orederBean.setNotify_url(jsonObject.getString("appNotifyUrl"));
                // orederBean.setNotify_url(Constant.URL_APPNOTIFY_Url);
            } else {
                orederBean.setNotify_url(Constant.URL_NOTIFY);
            }
            try {
                orederBean.setProduct_Name(jsonObject.getString("goodsName"));
            } catch (Exception e) {
                orederBean.setProduct_Name("订单付款");
                e.printStackTrace();
            }
            pay(context);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取支付流水号
     */
    @Override
    public void getOuttradenoFromServer(String orderID, int type) {
        Map<String, Object> map = new HashMap<>();
        if (list == null) {
            list = new ArrayList<>();
        } else {
            list.clear();
        }
        list.add(orderID);
        map.put("orderIDs", list);
        if (type == 1 || type == 15) {
            map.put("type", type);
        }
        Map<String, Object> rootMap = new HashMap<>();
        rootMap.put("map", map);
        rootMap.put("url", ConfirmOrderURL.ORDER_FIRM);
        rootMap.put("wat", LIST_ORDER);
        JSONRequest.getInstance().sendRequest(JSONRequest.POST, rootMap, handler,
                HttpUtil.ACTION_JSON);
    }

    @Override
    public void newPay(final Context context, JSONObject jsonObject) {
        Map map = new HashMap();
        map = OrangeDataHandler.getMapWithEntity(jsonObject);
        final String payInfo = String.valueOf(map.get("payInfo"));

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask((Activity) context);
                // 调用支付接口
                String result = alipay.pay(payInfo);

                Message msg = new Message();
                msg.what = APILAY_PAID;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void pay(final Context context) {
        String orderInfo = getOrderInfo();
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask((Activity) context);
                // 调用支付接口
                String result = alipay.pay(payInfo);

                Message msg = new Message();
                msg.what = APILAY_PAID;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * create the order info. 创建订单信息
     */
    public String getOrderInfo() {
        // 合作者身份ID
        String orderInfo = "partner=" + "\"" + orederBean.getPartner_id()
                + "\"";

        // 卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + orederBean.getAlipay_number()
                + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + orederBean.getOreder_Id() + "\"";


        // 商品名称
        orderInfo += "&subject=" + "\"" + orederBean.getProduct_Name() + "\"";

        // // 商品详情
        orderInfo += "&body=" + "\"" + orederBean.getDetail() + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + orederBean.getPrice() + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + orederBean.getNotify_url() + "\"";

        // 接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    public String sign(String content) {
        return SignUtils.sign(content, orederBean.getRas_Private());
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

}
